import json
import os
import time
import traceback
from json import JSONDecodeError
from urllib import parse

import requests


def send_request(url, params_dict={}, method="post", session=requests.session(), headers={}, cookies=""):
    """ 发送HTTP请求"""
    headers["User-Agent"] = "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.157 Mobile Safari/537.36"

    start_timestamp = time.time()
    if str(method).upper() == "POST":
        if session:
            resp = session.post(url, params_dict, headers=headers, cookies=cookies)
        else:
            resp = requests.post(url, params_dict, headers=headers, cookies=cookies)
    else:
        if session:
            data = parse.urlencode(params_dict)
            resp = session.get(url + "?" + data)
        else:
            resp = requests.get(url, params_dict, headers=headers, cookies=cookies)
    response_time_ms = round((time.time() - start_timestamp) * 1000, 2)
    try:
        case_resp = json.dumps(resp.json(), indent=4, ensure_ascii=False)
    except JSONDecodeError:
        case_resp = resp.text
    except Exception as e:
        case_resp = str(e)
        # print(e)

    try:
        log_msg = """
    method:%s
    case_url:%s
    response_time_ms:%s
    case_data:%s
    case_resp:%s
        """ % (method, url,response_time_ms, json.dumps(params_dict, indent=4, ensure_ascii=False), case_resp)
    except Exception as e:
        log_msg = """
    method:%s
    case_url:%s
    response_time_ms:%s
    case_data:%s
    case_resp:%s
            """ % (method, url,response_time_ms,params_dict, case_resp)
    print("-" * 150)
    s = traceback.extract_stack()
    if resp.status_code == 200:
        print(log_msg)
        try:
            update_tmp_db(s[-2][2], resp.json())
        except:
            pass
    else:
        print(resp.text)
    return resp, session


def get_tmp_db_info(k):
    """
    根据测试接口名(test_xxx)从临时数据库中获取接口响应
    :param k:
    :return:v:查询k的value，db_data:原始数据库
    """
    tmp_db = os.path.join(os.path.dirname(os.path.dirname((__file__))), "logs/pt_db.json")

    info = None
    with open(tmp_db, "r", encoding="utf8") as fp:
        db_data = json.load(fp)
    if k in db_data.get("pt_tmp_db").keys():
        info = db_data.get("pt_tmp_db").get(k)
    return info, db_data


def update_tmp_db(k, v):
    """ 更新本地测试数据库 """
    tmp_db = os.path.join(os.path.dirname(os.path.dirname((__file__))), "logs/pt_db.json")
    info, db_data = get_tmp_db_info("k")
    db_data["pt_tmp_db"][k] = v
    with open(tmp_db, "w", encoding="utf8") as fp:
        json.dump(db_data, fp, indent=4, ensure_ascii=False)
    return db_data


if __name__ == '__main__':
    print(get_tmp_db_info("manager_access_token"))
